try:
    import pymysql
except ImportError:
    print("❌ 错误: 未安装 pymysql 模块")
    print("请运行以下命令安装: pip install pymysql")

    exit(1)

from decimal import Decimal
from config import get_config
from model import UserInfo, CardInfo, TradeInfo, Deposit

def get_conn():
    """获取数据库连接"""
    try:
        # 获取当前环境配置
        config = get_config()
        
        # 数据库连接配置
        connection = pymysql.connect(
            host=config.DB_HOST,          # 数据库主机地址
            port=config.DB_PORT,          # 数据库端口
            user=config.DB_USER,          # 数据库用户名
            password=config.DB_PASSWORD,  # 数据库密码
            database=config.DB_NAME,      # 数据库名称
            charset=config.DB_CHARSET,    # 字符编码
            autocommit=False,             # 自动提交
            cursorclass=pymysql.cursors.DictCursor  # 使用字典游标
        )
        return connection
    except Exception as e:
        print(f"数据库连接失败: {e}")
        print(f"连接参数: host={config.DB_HOST}, port={config.DB_PORT}, user={config.DB_USER}, database={config.DB_NAME}")
        raise e

def test_connection():
    """测试数据库连接"""
    try:
        conn = get_conn()
        cursor = conn.cursor()
        cursor.execute("SELECT 1")
        result = cursor.fetchone()
        cursor.close()
        conn.close()
        print("✅ 数据库连接测试成功!")
        return True
    except Exception as e:
        print(f"❌ 数据库连接测试失败: {e}")
        return False

def setup_database():
    """设置数据库连接参数"""
    print("=== 数据库配置设置 ===")
    print("请根据您的MySQL数据库配置输入以下信息:")
    
    host = input("数据库主机地址 (默认: localhost): ").strip() or 'localhost'
    port = input("数据库端口 (默认: 3306): ").strip() or '3306'
    user = input("数据库用户名 (默认: root): ").strip() or 'root'
    password = input("数据库密码: ").strip()
    database = input("数据库名称 (默认: bank): ").strip() or 'bank'
    
    # 创建 .env 文件
    env_content = f"""# 数据库配置
DB_HOST={host}
DB_PORT={port}
DB_USER={user}
DB_PASSWORD={password}
DB_NAME={database}

# Flask 配置
FLASK_ENV=development
SECRET_KEY=your-secret-key-change-in-production
"""
    
    with open('.env', 'w', encoding='utf-8') as f:
        f.write(env_content)
    
    print(f"\n✅ 配置已保存到 .env 文件")
    print("现在可以运行以下命令测试连接:")
    print("python db.py")

if __name__ == "__main__":
    import sys
    
    if len(sys.argv) > 1 and sys.argv[1] == 'setup':
        setup_database()
    else:
        test_connection()
